from simpledcpp.core.base import DCPPPart, DCPPEvent
import sys

class ConnectionManager(DCPPPart):
	""" Connection manager. """
	def __init__(self, parent):
		DCPPPart.__init__(self, parent)
		self._connections = []
		self._cid = 0
		self.Events.Subscribe("ON_CREATE_CONNECTION", self._createConnection)
		self.Events.Subscribe("ON_DESTROY_CONNECTION", self._destroyConnection)

	def add(self, Connection):
		self._cid = self._cid + 1
		added = 0
		if Connection.direction == "Upload" and self.hasFreeUpload():
			added = 1
		elif Connection.direction == "Download" and self.hasFreeDownload():
			added = 1
		else:
			Connection.stop()
			del(Connection)
		if added:
			Connection.cid = self._cid
			self._connections.append(Connection)
			self.Event(DCPPEvent("ON_NEW_CONNECTION",(Connection,)))
			Connection.start()

	def _destroyConnection(self, Event):
		self.remove(Event.userdata[0])
	def _createConnection(self, Event):
		self.add(Event.userdata[0])

	def remove(self, Connection):
		Connection.stop()
		self._connections.remove(Connection)

	def stop(self):
		pass

	def hasFreeUpload(self):
		count = 0
		for i in self._connections:
			if i.direction == "Upload":
				count = count + 1
		if int(self.settings.get("upload_slots")) <= count:
			return False
		return True

        def hasFreeDownload(self):
                count = 0
                for i in self._connections:
                        if i.direction == "Download":
                                count = count + 1
                if int(self.settings.get("download_slots")) <= count:
                        return False
                return True

